package utils.global.fliters;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

@Aspect
public class XssAop {

    @Autowired
    XssProperties xssProperties;

    @Pointcut("@annotation(xssClear)")
    public void xssMethod(XssClear xssClear) {
    }

    @Around(value = "xssMethod(xssClear)", argNames = "joinPoint,xssClear")
    public Object xssAop(ProceedingJoinPoint joinPoint, XssClear xssClear) throws Throwable {
        boolean cleared = false;

        Object[] args = joinPoint.getArgs();

        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        Annotation[][] parameterAnnotations = method.getParameterAnnotations();
        for (int i = 0; i < parameterAnnotations.length; i++) {
            for (int j = 0; j < parameterAnnotations[i].length; j++) {
                if (parameterAnnotations[i][j] instanceof XssClearField) {
                    args[i] = cleanXSS(args[i].toString());
                    cleared = true;
                }
            }
        }

        if (!cleared) {
            for (int i = 0; i < args.length; i++) {
                args[i] = cleanXSS(args[i].toString());
            }
        }

        return joinPoint.proceed(args);

    }

    public String cleanXSS(String value) {
        value = value.replaceAll("<", "&lt;").replaceAll(">", "&gt;");
        value = value.replaceAll("%3C", "&lt;").replaceAll("%3E", "&gt;");
        value = value.replaceAll("\\(", "&#40;").replaceAll("\\)", "&#41;");
        value = value.replaceAll("%28", "&#40;").replaceAll("%29", "&#41;");
        value = value.replaceAll("'", "&#39;");
        value = value.replaceAll("eval\\((.*)\\)", "");
        value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
        value = value.replaceAll("script", "");
        String[] ignore = xssProperties.getIgnore();
        for (int i = 0; i < ignore.length; i += 2) {
            value = value.replaceAll(ignore[i], ignore[i + 1]);
        }
        return value;
    }
}
